const express = require('express')
const multer = require('multer')
const fs = require('fs')
const router = express.Router()

const Introduce = require('../../models/Introduce')

//添加介绍
router.post('/add', multer({
  dest: 'asset/introduce'
}).array('file', 10), (req, res) => {
  let files = req.files;
  if (files.length === 0) {
    res.render("error", {message: "上传文件不能为空！"});
    return
  } else {
    let fileInfo = {};
    for (let i in files) {
      let file = files[i];
      fs.renameSync(file.path, `asset/introduce/${file.originalname}`)
      if (file.originalname.indexOf('Logo') !== -1) {
        fileInfo.logo = 'http://localhost:5000/api/introduce/introduceInf?url=' + file.originalname
      } else {
        fileInfo.picture = 'http://localhost:5000/api/introduce/introduceInf?url=' + file.originalname
      }
    }
    fileInfo.title = req.body.title
    fileInfo.hobby = req.body.hobby
    fileInfo.content = req.body.content
    fileInfo.information = req.body.information
    console.log(fileInfo)
    new Introduce(fileInfo).save().then(music => {
      res.json(music)
    })
  }
})

router.get('/introduceInf', (req, res) => {
  req.query.url ? res.download(`asset/introduce/${req.query.url}`) : res.send({
    success: false
  })
})

//查询
router.get('/', (req, res) => {
  Introduce.find()
    .then(introduce => {
      if (!introduce) {
        return res.status(404).json('没有任何内容')
      }
      res.json(introduce)
    })
    .catch(err => res.status(404).json(err))
})

//查询单个
router.get('/:id', (req, res) => {
  Introduce.findOne({
    _id: req.params.id
  })
    .then(introduce => {
      if (!introduce) {
        return res.status(404).json('没有任何内容')
      }
      res.json(introduce)
    })
    .catch(err => res.status(404).json(err))
})

module.exports = router
